<?php

namespace app\api\model\admin\setting;

use app\api\common\model\BaseModel;
use app\api\common\traits\ModelTrait;
use think\db\Query;

/**
 * 管理员权限规则
 * Class User
 *
 * @package app\model\admin
 */
class Dept extends BaseModel
{
    use ModelTrait;

    protected $connection = 'mysql';
    /**
     * 数据表主键
     *
     * @var string
     */
    protected $pk = 'id';

    /**
     * 模型名称
     *
     * @var string
     */
    protected $name = 'admin_departments';

    //软删除，查询时会自动加上 xxx IS NULL
    use \think\model\concern\SoftDelete;

    protected string $deleteTime = 'delete_time';

    /**
     * 搜索器
     *
     * @param \think\db\Query $query
     * @param string          $value
     */
    public function searchNameLikeAttr(Query $query, string $value)
    {
        if ($value) {
            $query->whereLike('name', '%' . $value . '%');
        }
    }

    /**
     * 搜索器
     *
     * @param $query
     * @param $value
     */
    public function searchIdInAttr($query, $value)
    {
        if ($value) {
            $query->whereIn('id', $value);
        }
    }

    /**
     * 递归查询子数据
     *
     * @param int $pid
     * @param int $level
     *
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getChildren($pid = 0, $level = 0)
    {
        $result   = [];
        $children = $this->where('pid', $pid)->select()->toArray();
        foreach ($children as $child) {
            $child['level']    = $level;
            $child['children'] = $this->getChildren($child['id'], $level + 1);
            $result[]          = $child;
        }
        return $result;
    }

    //withSearch不能查询$value为null的，必须配置查询器
//    public function searchDeleteTimeAttr($query, $value)
//    {
//        $query->where('delete_time', $value);
//    }

}
